﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PartyCraftServer.Commands;
using System.Reflection;
using System.Security.Policy;
using System.IO;
using System.Threading;

namespace PartyCraftServer.Plugins
{
    public class PluginManager
    {
        public List<Assembly> InstalledAssemblies { get; set; }

        public PluginManager()
        {
            InstalledAssemblies = new List<Assembly>();
        }

        internal void InstallPlugin(string pluginPath)
        {
            PartyCraft.SendToOps("§9Installing plugin: " + Path.GetFileName(pluginPath));
            Command.CommandsEnabled = false;
            Command.ReasonForDisabled = "Commands are disabled while a new plugin is installed.";
            Assembly a = Assembly.LoadFile(pluginPath);
            if (InstalledAssemblies.Contains(a))
            {
                PartyCraft.SendToOps("§9Plugin is already installed!");
                Command.CommandsEnabled = true;
                Command.ReasonForDisabled = "";
                return;
            }
            Type plugin = a.GetTypes().Where(t => typeof(Plugin).IsAssignableFrom(t)).First();
            Plugin p = (Plugin)Activator.CreateInstance(plugin);
            InstalledAssemblies.Add(a);

            PartyCraft.SendToOps("§9" + p.Name + " was successfully installed!");
            if (p.RequiresRestart)
                PartyCraft.SendToOps("§9A server restart is required.");
            else
            {
                Command.CommandsEnabled = true;
                Command.ReasonForDisabled = "";
            }
            Thread thread = new Thread(new ThreadStart(p.OnInstall));
            thread.Start();
        }

        internal void UninstallPlugin(string pluginPath)
        {
        }
    }
}
